package com.atguigu.gulimall.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * 跨域统一配置
 *
 * @author LaiSanShan
 * @date 2021-07-14
 */
@Configuration
public class GulimallCorsConfiguration {

    /**
     * 配置跨域Filter
     *
     * @return 跨域Filter
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        // 使用CorsConfigurationSource的实现类进行配置Filter
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        // 配置跨域配置
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        // TODO 跨域配置，临时方案：需要origin具体前端路径
        /*
          1.当前端配置withCredentials=true时, 后端配置Access-Control-Allow-Origin不能为*, 必须是相应地址
          2.当配置withCredentials=true时, 后端需配置Access-Control-Allow-Credentials
          3.当前端配置请求头时, 后端需要配置Access-Control-Allow-Headers为对应的请求头集合
          前端配置：
            withCredentials: true,
            http.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest' // 判断是否为ajax请求
         */
//        corsConfiguration.setAllowedOriginPatterns(Collections.singletonList("*"));
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);
        // 注册跨域配置
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsWebFilter(urlBasedCorsConfigurationSource);
    }

}
